﻿using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.AppointAPI.Ganzhou;
using AngleSharp.Io;
using Azure;
using ClosedXML.Utils;
using FluentFTP;
using Masuit.Tools;
using Masuit.Tools.Reflection;
using Microsoft.IdentityModel.Tokens;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Policy;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using static AJWPFAdmin.Services.AppointAPI.DefaultAppointAPI;

namespace AJWPFAdmin.Services.AppointAPI.ChengDu
{
    public class ChengDuAppointAPI : AppointAPIBase
    {
        private APIConfig _apiConfig;

        public ChengDuAppointAPI(ApplicationType appType,
         SystemConfigDictionary cfg,
         IContainerProvider svcProvider) : base(appType, cfg, svcProvider)
        {

        }

        private static readonly Dictionary<CarPlateColor, string> _customCarPlateColorMaps = new Dictionary<CarPlateColor, string>
        {
            {CarPlateColor.蓝牌, "蓝牌"},
            {CarPlateColor.黄牌, "黄牌"},
            {CarPlateColor.白牌, "白牌"},
            {CarPlateColor.黑牌, "黑牌"},
            {CarPlateColor.新能源绿牌, "新能源绿牌"},
            {CarPlateColor.其他, "其他"},
            {CarPlateColor.渐变绿牌, "新能源绿黄牌"},
            {CarPlateColor.新能源黄牌, "新能源绿黄牌"},
        };
        public string SocketSend(string data)
        {
            Socket socket = null;
            try
            {
                //_logger.Info($"Start ChengDuAppointAPI--SocketSend {data}");
                // 创建Socket对象，指定使用IPv4地址族、面向连接的流套接字类型和TCP协议
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 连接服务器，指定服务器IP地址和端口号
                IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(_apiConfig.url), Convert.ToInt32(_apiConfig.port));
                socket.Connect(serverEndPoint);
                // 发送数据，将数据转换为字节数组后发送
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                socket.Send(buffer);

                // 接收服务器响应，创建字节数组用于接收响应数据
                byte[] responseBuffer = new byte[1024];
                int receivedBytes = socket.Receive(responseBuffer);
                string response = Encoding.UTF8.GetString(responseBuffer, 0, receivedBytes);

                return response;
            }
            catch (Exception ex)
            {
                _logger.Error($"ChengDuAppointAPI--SocketSend-req:{data} ex: {ex}");
                return null;
            }
            finally
            {
                if (socket != default)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }
            }
        }

        protected override void OnAPILogsRaised(PassagewayDirection? direction,
         string logs)
        {
            base.OnAPILogsRaised(direction, logs);
        }

        public override Task<ProcessResult> UploadCarInfoAsync(CarInfoParams @params)
        {
            return Task.FromResult(ProcessResult.DefaultSuccess);
        }

        public override Task<ProcessResult> UploadComanyInfoAsync(string @params)
        {
            var result = new ProcessResult();
            try
            {
                //var req = CommonUtil.TryGetJSONObject<ChengDuUploadComanyInfoReq>(@params);
                //if (req == default)
                //{
                //    result.SetError("req is null");
                //    _logger.Error($"ChengDuAppointAPI--UploadComanyInfoAsync error: req is null");
                //}
                // 精确到毫秒的时间戳，用于唯一标识一次命令交互
                string qn = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                // 类型编码，31表示门禁视频信息
                string st = "31";
                // 数据类型编码，60002表示上传的数据为门禁视频信息数据
                string cn = "60003";
                // 企业统一社会信用代码，需替换为实际代码
                string mn = _apiConfig.unifiedcreditcode;
                // 上传时间，格式为yyyyMMddHHmmss
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                // 企业门禁监控系统状态
                string f_qymjjkzt = _apiConfig.qymjjkzt;
                // 生产情况
                string f_scqk = _apiConfig.scqk;                
                // 标记，默认值为5
                string flag = "5";
                // 指令参数，默认值为&&
                string cp = "&&";
                // 答应，默认值为:30&&A9C1
                string rtdInterval = "30&&A9C1";

                string data = $"##QN={qn};ST={st};CN={cn};MN={mn};DATE={date};F_QYMJJKZT={f_qymjjkzt};F_ SCQK={f_scqk};Flag={flag};CP={cp};RtdInterval={rtdInterval}\r\n";
                var res = SocketSend(data);
                if (res != default && res.StartsWith("1"))
                {
                    result.SetSuccess();
                    _logger.Info($"ChengDuAppointAPI--UploadComanyInfoAsync-success-成都市-上传企业信息成功!");
                }
                else
                {
                    result.SetError(res);
                    _logger.Error($"ChengDuAppointAPI--UploadComanyInfoAsync error: {res}");
                }
                return Task.FromResult(ProcessResult.DefaultSuccess);
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"ChengDuAppointAPI--UploadComanyInfoAsync error: {ex.Message}");
            }

            return Task.FromResult(result);
        }

        public override Task<ProcessResult> UploadDeviceInfoAsync(DeviceInfoParams @params)
        {
            var result = new ProcessResult();
            try
            {
                // 精确到毫秒的时间戳，用于唯一标识一次命令交互
                string qn = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                // 类型编码，31表示门禁视频信息
                string st = "31";
                // 数据类型编码，60002表示上传的数据为门禁视频信息数据
                string cn = "60002";
                // 企业统一社会信用代码，需替换为实际代码
                string mn = _apiConfig.unifiedcreditcode;
                // 上传时间，格式为yyyyMMddHHmmss
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                // 视频位置
                string f_wz = @params.Device?.Name;//_apiConfig.videoPlace;
                // 视频地址
                string f_dz = @params.Device?.VideoPlayRTSPUrl;//_apiConfig.videoUrl;
                // 视频端口
                string f_port = @params.Device?.Port.ToString();// _apiConfig.videoPort;
                // 视频用户名
                string f_uid = @params.Device?.LoginName;//_apiConfig.videousername;
                // 视频密码
                string f_psd = @params.Device?.LoginPassword;  //_apiConfig.videopassword;
                // 标记，默认值为5
                string flag = "5";
                // 指令参数，默认值为&&
                string cp = "&&";
                // 答应，默认值为:30&&A9C1
                string rtdInterval = "30&&A9C1";

                string data = $"##QN={qn};ST={st};CN={cn};MN={mn};DATE={date};F_WZ={f_wz};F_DZ={f_dz};F_PORT={f_port};F_UID={f_uid};F_PSD={f_psd};Flag={flag};CP={cp};RtdInterval={rtdInterval}\r\n";
                var res = SocketSend(data);
                if (res != default && res.StartsWith("1"))
                {
                    result.SetSuccess();
                    _logger.Info($"ChengDuAppointAPI--UploadDeviceInfoAsync-success-成都市-上传视频信息成功!");
                }
                else
                {
                    result.SetError(res);
                    _logger.Error($"ChengDuAppointAPI--UploadDeviceInfoAsync error: {res}");
                }
                return Task.FromResult(ProcessResult.DefaultSuccess);
            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"ChengDuAppointAPI--UploadDeviceInfoAsync error: {ex.Message}");
                return Task.FromResult(ProcessResult.DefaultSuccess);
            }
        }

        public override async Task<ProcessResult> UploadShippingRecordAsync(ShippingRecordParams @params)
        {
            var result = new ProcessResult();
            try
            {
                // 精确到毫秒的时间戳，用于唯一标识一次命令交互
                string qn = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                // 类型编码，31表示车辆进出门禁记录
                string st = "31";
                // 数据类型编码，60001表示上传的数据为车辆进出门禁记录
                string cn = "60001";
                // 企业统一社会信用代码，需替换为实际代码
                string mn = _apiConfig.unifiedcreditcode;
                // 进出时间，格式为yyyyMMddHHmmss
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                // 进厂/出厂照片（车头、车身）的Base64编码，这里假设为空，实际需填充
                string f_jczp = "";
                var carNo = @params.Record.CarNo;
                var (carHead, plate, carTail) = @params.Record.GetWatchPositionImageFile(@params.Record.Direction);
                _logger.Info($"UploadShippingRecordAsync-request{CommonUtil.AJSerializeObject(@params.Record)}");
                _logger.Info($"UploadShippingRecordAsync-carHead的值：{carHead} {plate} {carTail}");
                await Task.Delay(3 * 1000);
                //r.CompleteFileUrls(_carIdentificationConfig, nameof(r.InCaptureFile));
                //r.CompleteFileUrls(_carIdentificationConfig, nameof(r.OutCaptureFile));

                var carHeadBase64ImageString = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, carHead));
                var carTailBase64ImageString = CommonUtil.GetBase64FromLocalOrHttpFile(_carIdentificationConfig.CompleteFileUrl(carNo, carTail));
                // 是否企业自有车辆，1表示是，0表示否
                var vehicleRes = await GetEledgerVehicleInfoAsync(@params.Record.CarNo, @params.Record.Direction);
                if (!vehicleRes.Success)
                {
                    result.SetError(vehicleRes.Message);
                    return result;
                }

                if (vehicleRes.Data == null)
                {
                    result.SetError($"{SystemConfigKey.APIDefault.GetDescription()} 未查询到车辆信息");
                    return result;
                }

                var eledgerCarInfo = vehicleRes.Data as Eledger_VehicleInfo ?? new Eledger_VehicleInfo();
                int f_sfqyzycl = @params.Record.IsOwnedByCompany == "是" ? 1 : 0;//eledgerCarInfo.Reserve1 == "是" ? 1 : 0;

                // 进出位置
                string f_jcwz = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.WatchhouseName : @params.Record.OutWatchhouseName;
                // 车牌号码
                string f_cphm = @params.Record.CarNo;
                // 车牌颜色
                string f_cpys = _customCarPlateColorMaps[@params.Record.PlateColor];
                // 进出类型（进或出）
                string f_jclx = @params.Record.Direction == PassagewayDirection.进 ? "进" : "出";
                // 出入口编号，根据规则生成，这里假设为A
                string f_crkbh = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.WatchhouseCode : @params.Record.OutWatchhouseCode;
                // 道闸编号，根据规则生成，这里假设为A01
                string f_zdbh = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.PassagewayCode : @params.Record.OutPassagewayCode;
                // 车辆识别代号
                string f_vin = @params.Record.VIN;
                // 注册登记日期，格式为YYYYMMDD
                string f_zcdjrq = @params.Record.RegDate?.ToString("yyyyMMdd");
                // 车辆类型，参照GA/T16
                string f_cllx = @params.Record.TruckTypeName;
                // 车辆品牌型号，例如一汽大众速腾
                string f_clppxh = AppendUnderscoreIfPure(@params.Record.CarBrandModel); 
                _logger.Info($"ChengDuAppointAPI--UploadShippingRecordAsync--车辆品牌型号处理后: {f_clppxh}");
                // 燃料类型，参照GA/T16
                string f_yllx = @params.Record.FuelTypeName;
                // 排放标准
                string f_pfbz = @params.Record.EmissionStandard switch
                {
                    EmissionStandard.国一 => "国一",
                    EmissionStandard.国三 => "国三",
                    EmissionStandard.国二 => "国二",
                    EmissionStandard.国五 => "国五",
                    EmissionStandard.国六 => "国六",
                    EmissionStandard.国四 => "国四",
                    EmissionStandard.国零 => "国一",
                    EmissionStandard.未知 => "国一",
                    EmissionStandard.电动 => "电动",
                    _ => "国一" // _ 表示默认情况（类似 default）
                };
                // 联网状态，0表示未联网，1表示已联网
                int f_lwzt = @params.Record.NetworkingStatus ? 1 : 0;
                // 使用性质，参照GA/T16
                string f_syxz = @params.Record.UsageDescription;
                // 运输货物名称
                string f_hwmc = @params.Record.Direction == PassagewayDirection.进 ? @params.Record.InGoodsName : @params.Record.OutGoodsName;
                // 运输量
                float f_ysl = @params.Record.Direction == PassagewayDirection.进 ? (float)@params.Record.InGoodsVolume : (float)@params.Record.OutGoodsVolume;
                // 运输量单位
                string f_ysldw = @params.Record.FreightUnit switch 
                { 
                     FreightUnit.吨 => "吨",
                     FreightUnit.升 => "升",
                     FreightUnit.千克 => "吨",
                     FreightUnit.包 => "包", 
                     _ => "包"
                };
                // 车队名称（自有、个人或运输公司营业执照名称）
                string f_cdmc = @params.Record.TeamName;
                // 抬杆方式（手动或自动）
                string f_tgfs = @params.Record.AutoPass ? "自动" : "手动";
                // 车载终端7日数据，0表示不正常，1表示正常
                int f_czzdqrsj = 1;
                // 标记，默认值为5
                string flag = "5";
                // 指令参数，默认值为&&
                string cp = "&&";
                // 答应，默认值为:30&&A9C1
                string rtdInterval = "30&&A9C1";
                //_logger.Debug($"成都上传进出台帐车辆照片: {base64ImageString}");
                // 移除前缀，保留纯Base64部分 
                if (carHeadBase64ImageString.StartsWith("data:image"))
                {
                    int commaIndex = carHeadBase64ImageString.IndexOf(',');
                    if (commaIndex > 0)
                    {
                        carHeadBase64ImageString = carHeadBase64ImageString.Substring(commaIndex + 1);
                    }
                }
                f_jczp = HttpUtility.UrlEncode(carHeadBase64ImageString, System.Text.Encoding.UTF8); 
                string data = $"##QN={qn};ST={st};CN={cn};MN={mn};DATE={date};F_JCZP={f_jczp};F_JCWZ={f_jcwz};F_CPHM={f_cphm};F_CPYS={f_cpys};F_JCLX={f_jclx};F_CRKBH={f_crkbh};F_ZDBH={f_zdbh};F_VIN={f_vin};F_ZCDJRQ={f_zcdjrq};F_CLLX={f_cllx};F_CLPPXH={f_clppxh};F_YLLX={f_yllx};F_PFBZ={f_pfbz};F_LWZT={f_lwzt};F_SYXZ={f_syxz};F_HWMC={f_hwmc};F_YSL={f_ysl};F_YSLDW={f_ysldw};F_CDMC={f_cdmc};F_TGFS={f_tgfs};F_CZZDQRSJ={f_czzdqrsj};F_SFQYZYCL={f_sfqyzycl};Flag={flag};CP={cp};RtdInterval={rtdInterval}\r\n";
                var res = SocketSend(data);
                if (res != default && res.StartsWith("1"))
                {
                    result.SetSuccess();
                    _logger.Info($"ChengDuAppointAPI--UploadShippingRecordAsync-success-上传成功!");
                }
                else
                {
                    result.SetError(res);
                    _logger.Error($"ChengDuAppointAPI--UploadShippingRecordAsync error1: {res}");
                }

            }
            catch (Exception ex)
            {
                result.SetError(ex.Message);
                _logger.Error($"ChengDuAppointAPI--UploadShippingRecordAsync error2: {ex.Message} {ex.StackTrace}");
            }
            return result;
        }

        public string AppendUnderscoreIfPure(string input)
        {
            if (string.IsNullOrEmpty(input))
                return "_";

            string result = input;
            bool isPureChinese = Regex.IsMatch(result, @"^[\u4e00-\u9fa5]+$"); // 纯中文检测 [1,6](@ref)
            bool isPureAlphanumeric = Regex.IsMatch(result, @"^[a-zA-Z0-9]+$"); // 纯字母数字检测 [2](@ref)

            if (isPureChinese || isPureAlphanumeric)
            {
                result += "_";
            }
            else
            {
                // 正则说明：([\u4e00-\u9fa5]) 匹配一个中文字符 → (?=[a-zA-Z0-9]) 正向预查其后紧跟字母/数字
                string pattern = @"([\u4e00-\u9fa5])(?=[a-zA-Z0-9])";
                result = Regex.Replace(input, pattern, "$1_");
            }
            return result;
        }

        public override Task ConvertToCustomConfig(bool isReal)
        {
            _apiConfig = CommonUtil.TryGetJSONObject<APIConfig>(Config.StringValue) ?? new APIConfig();
            _customAPIConfig = _apiConfig;
            AutoUploadDataVerification = _apiConfig.AutoUploadDataVerification;

            if (isReal)
            {

            }
            else
            {
                _ = GetSchemas();
            }

            return Task.CompletedTask;
        }

        public new void Dispose()
        {

        }
        public class APIConfig : APIConfigBase
        {
            [DynamicFormItemDefine("接口地址")]
            public string url { get; set; }
            [DynamicFormItemDefine("接口端口号")]
            public string port { get; set; }
            //[DynamicFormItemDefine("接口用户名")]
            //public string username { get; set; }

            //[DynamicFormItemDefine("接口密码")]
            //public string password { get; set; }

            //[DynamicFormItemDefine("文件上传地址")]
            //public string ftpUrl { get; set; }
            //[DynamicFormItemDefine("文件上传端口号")]
            //public string ftpPort { get; set; }

            //[DynamicFormItemDefine("文件上传用户名")]
            //public string ftpusername { get; set; }

            //[DynamicFormItemDefine("文件上传密码")]
            //public string ftppassword { get; set; }

            [DynamicFormItemDefine("企业名称")]
            public string companyname { get; set; }

            //[DynamicFormItemDefine("企业简称")]
            //public string companyjc { get; set; }

            //[DynamicFormItemDefine("企业编码")]
            //public string companycode { get; set; }

            [DynamicFormItemDefine("统一信用代码")]
            public string unifiedcreditcode { get; set; }

            [DynamicFormItemDefine("企业门禁监控系统状态", VbenAdminFormType.Select, OptionsHandler = typeof(QYMJJKZTOptionsHandler))]
            public string qymjjkzt { get; set; }

            [DynamicFormItemDefine("生产情况", VbenAdminFormType.Select, OptionsHandler = typeof(SCQKOptionsHandler))]
            public string scqk { get; set; }

            //[DynamicFormItemDefine("视频地址")]
            //public string videoUrl { get; set; }
            //[DynamicFormItemDefine("视频端口号")]
            //public string videoPort { get; set; }
            //[DynamicFormItemDefine("视频位置")]
            //public string videoPlace { get; set; }

            //[DynamicFormItemDefine("视频用户名")]
            //public string videousername { get; set; }

            //[DynamicFormItemDefine("视频密码")]
            //public string videopassword { get; set; }

            //[DynamicFormItemDefine("法人代表")]
            //public string corpname { get; set; }

            //[DynamicFormItemDefine("行业类型编码")]
            //public string industrytypecode { get; set; }

            //[DynamicFormItemDefine("行业类型名称")]
            //public string industrytypename { get; set; }
            //[DynamicFormItemDefine("企业地址")]
            //public string address { get; set; }
            //[DynamicFormItemDefine("区县编码")]
            //public string countycode { get; set; }
            //[DynamicFormItemDefine("区县名称")]
            //public string countyname { get; set; }
            //[DynamicFormItemDefine("产能")]
            //public string cn { get; set; }
            //[DynamicFormItemDefine("监控设备数量")]
            //public string jksbsl { get; set; }
            //[DynamicFormItemDefine("企业评级")]
            //public string industry_type { get; set; }
            //[DynamicFormItemDefine("经度")]
            //public string lng { get; set; }
            //[DynamicFormItemDefine("纬度")]
            //public string lat { get; set; }
        }
    }
}
